<template>
  <div>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem" />
  </div>
  <el-dialog v-model="addOrUpdateVisible" :title="title" :before-close="handleClose">
    <div>
      <el-form ref="orgRef" label-width="140px" :model="form" :rules="rules" :disabled="isView">
        <el-form-item label="机构名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入机构名称" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="社会统一信用代码" prop="socialCode">
          <el-input v-model="form.socialCode" :maxlength="18" placeholder="请输入社会统一信用代码" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="typeCode">
          <el-radio v-model="form.typeCode" label="institution">机构</el-radio>
          <el-radio v-model="form.typeCode" label="association">协会</el-radio>
        </el-form-item>
        <el-form-item label="是否默认机构" prop="defaultFlag">
          <el-radio v-model="form.defaultFlag" :label="1">是</el-radio>
          <el-radio v-model="form.defaultFlag" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="登录账号" prop="userName">
          <el-input v-model="form.userName" :maxlength="11" placeholder="请输入登录账号" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item v-if="isAdd" label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item v-if="isAdd" label="确认密码" prop="rePassword">
          <el-input v-model="form.rePassword" placeholder="请再次确认密码" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="机构代码" prop="organCode">
          <el-input v-model="form.organCode" :maxlength="2" @input="validateInput" placeholder="请输入机构代码"
            style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactPhone">
          <el-input v-model="form.contactPhone" :maxlength="11" placeholder="请输入联系方式" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="机构地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入机构地址" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :autosize="{ minRows: 3, maxRows: 5 }"
            :maxlength="1000" :show-word-limit="true"></el-input>
        </el-form-item>
      </el-form>

    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="!isView" @click="addOrUpdateVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import tablePaging from '@/views/common/component/table-paging'
import { onMounted, reactive, ref, watch } from 'vue'
import {
  tableItem,
  operationItem,
  orgInfoApi,
  orgAddApi,
  orgEditApi,
  orgRePasswordApi,
  orgChangeStatusApi,
} from './const.js'
import { ElMessage } from 'element-plus'
import { validateCreditCode } from '../../../../utils/validate'
import { clearForm } from '../../../../utils'
import { orgListApi } from '../enterprise/const'
const { proxy } = getCurrentInstance();
const title = ref('');
const isAdd = ref(false);
const isView = ref(false);
const addOrUpdateVisible = ref(false);
const orgRef = ref('')
const handleClose = () => {
  reset();
  addOrUpdateVisible.value = false;
};
const organCode = ref('')
const form = reactive({
  userId: '',
  nickName: '',
  socialCode: '',
  typeCode: '',
  defaultFlag: 0,
  userName: '',
  password: '',
  rePassword: '',
  organCode: '',
  contactName: '',
  contactPhone: '',
  address: '',
  remark: '',
  postIds: [],
  roleIds: []
},)
//校验密码
const equalToPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请输入确认密码"));
  } else if (form.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};
//校验机构代码
const validateInput = () => {
  const regex = /^[A-Za-z]{0,2}$/;
  if (!regex.test(form.organCode)) {
    form.organCode = form.organCode.slice(0, 2).replace(/[^A-Za-z]/g, '');
  }
};
const rules = ({
  nickName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
  socialCode: [{ required: true, validator: validateCreditCode, trigger: 'blur' }],
  typeCode: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  defaultFlag: [{ required: true, message: '请选择是否默认机构', trigger: 'blur' }],
  userName: [{ required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的登录手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
  rePassword: [{ required: true, validator: equalToPassword, trigger: 'blur' }],
  organCode: [{ required: true, message: '请输入机构代码', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [{ required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
})

onMounted(() => {
  setOptionsList()
})

// 搜索
operationItem.menuArray[0].handle = () => {
  clickSearch()
}
// 新增
operationItem.menuArray[1].handle = () => {
  clickAdd()
}
//查看
tableItem.btnArray[0].handle = (row) => {
  clickViewOrEdit('view', row)
}
//修改
tableItem.btnArray[1].handle = (row) => {
  clickViewOrEdit('edit', row)
}
//重置密码
tableItem.btnArray[2].handle = (row) => {
  clickResetPwd(row)
}
//禁用
tableItem.btnArray[3].handle = (row) => {
  clickChangeStatus(row)
}
//启用
tableItem.btnArray[4].handle = (row) => {
  clickChangeStatus(row)
}

function clickSearch() {
  tableItem.pageInfo.paging()
}
function clickAdd() {
  reset();
  addOrUpdateVisible.value = true;
  title.value = "新增机构";
  isAdd.value = true
  isView.value = false
}
function clickViewOrEdit(type, row) {
  addOrUpdateVisible.value = true;
  isAdd.value = false
  proxy.resetForm('orgRef')
  if (type === 'view') {
    title.value = "机构信息";
    isView.value = true
  }
  if (type === 'edit') {
    title.value = "修改机构";
    isView.value = false
  }
  orgInfoApi(row.userId).then(res => {
    Object.keys(form).forEach((key) => { form[`${key}`] = res.data[`${key}`] })
    form.postIds = res.postIds
    form.roleIds = res.roleIds
  });
}
function setOptionsList() {
  let dataRequest = {
    nickName: '',
    typeCodeList: ['institution', 'association']
  }
  orgListApi(dataRequest).then(res => {
    const orgList = res.rows || res.data
    orgList.map(item => {
      operationItem.SearchItem[0].options.push({ label: item.nickName, value: item.nickName })
    })
  })
}
//提交表单
function submitForm() {
  if (!isView.value) {
    proxy.$refs["orgRef"].validate(valid => {
      if (valid) {
        if (isAdd.value) {
          orgAddApi(form).then(res => {
            ElMessage.success('新增成功');
            addOrUpdateVisible.value = false;
            tableItem.pageInfo.paging()
          })
        } else {
          orgEditApi(form).then(res => {
            ElMessage.success('修改成功');
            addOrUpdateVisible.value = false;
            tableItem.pageInfo.paging()
          })
        }
      }
    })
  } else {
    addOrUpdateVisible.value = false;
  }
}

//重置密码
function clickResetPwd(row) {
  proxy.$modal.confirm('密码重置后新密码为账号后六位，确认要重置【' + row.nickName + '】的密码吗?').then(function () {
    let dataRequest = {
      userId: row.userId,
      typeCode: row.typeCode
    }
    return orgRePasswordApi(dataRequest);
  }).then(res => {
    ElMessage.success(res.msg);
  }).catch(() => { });
}
//禁用/启用
function clickChangeStatus(row) {
  console.log('row', row)
  let text = row.status === "0" ? "禁用" : "启用";
  proxy.$modal.confirm('确认要' + text + '【' + row.nickName + '】用户吗?').then(function () {
    let dataRequest = {
      userId: row.userId,
      status: row.status === '0' ? '1' : '0'
    }
    return orgChangeStatusApi(dataRequest);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
    tableItem.pageInfo.paging()
  }).catch(() => { });
}
//清空表单
function reset() {
  clearForm(form)
  form['defaultFlag'] = 0;
  form.postIds = []
  form.roleIds = []
  proxy.resetForm("orgRef");
}
</script>
<style></style>
